﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;

namespace DFGK_WMS.Repository
{
    public class RFIDRepository : BaseRepository<TInventory>, IRFIDRepository
    {
        public RFIDRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }

        public bool UpdRFID(List<TPriceTags> tags)
        {
            Context.TPriceTags.AddRange(tags);
            if (Context.SaveChanges() <= 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 标签点亮接口
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public RFIDMsgDto LightUp(string path, object data)
        {
            RFIDMsgDto rfidMsgDto = new RFIDMsgDto();

            try
            {
                //string wcsUrl = "http://172.16.99.12:28086/";
                string wcsUrl = "localhost/";
                string url = wcsUrl + path;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                string jsonData = JsonConvert.SerializeObject(data);

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonData);
                }



                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // 检查响应状态码
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string jsonResponse = reader.ReadToEnd(); // 读取服务器响应的内容
                            rfidMsgDto = JsonConvert.DeserializeObject<RFIDMsgDto>(jsonResponse);
                            if (rfidMsgDto.error_code != 1)
                            {
                                return rfidMsgDto;
                            }
                        }
                        rfidMsgDto.error_code = 0;
                        rfidMsgDto.error_msg = "成功";
                        return rfidMsgDto;
                    }
                    else
                    {
                        rfidMsgDto.error_code = 1;
                        rfidMsgDto.error_msg = "HTTP请求失败，状态码：" + response.StatusCode;
                        return rfidMsgDto;
                    }
                }
            }
            catch (Exception)
            {
                // 处理异常情况
                rfidMsgDto.error_code = 1;
                rfidMsgDto.error_msg = "HTTP请求失败，状态码：500";
                return rfidMsgDto;
            }

        }

        /// <summary>
        /// 获取巷道
        /// </summary>
        /// <param name="cellCode"></param>
        /// <returns></returns>
        public List<TRouteway> GetTroutway(out string msg,List<string> cellCode)
        {
            msg = "";
            try
            {
                List<TRouteway> routeways = new List<TRouteway>();
                foreach (string cell in cellCode)
                {
                    var cellModel = Context.TCells.FirstOrDefault(x => x.Code == cell);
                    if (cellModel == null)
                    {
                        continue;
                    }
                    var shelvesModel = Context.TShelves.FirstOrDefault(x => x.Code == cellModel.ShelfCode);
                    var routway = Context.TRouteways.FirstOrDefault(x => x.Id == shelvesModel.RoutewayId);
                    routeways.Add(routway);
                }
                return routeways.GroupBy(x => x.Code)
                                .Select(g => g.First())
                                .ToList();
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 根据巷道查询巷道灯
        /// </summary>
        /// <param name="routeways"></param>
        /// <returns></returns>
        public RoadwayLightUpDto GetLightByRoadway(out string msg, List<string> cellCode, List<TRouteway> routeways)
        {
            msg = "";
            RoadwayLightUpDto  roadwayLightUpDto = new RoadwayLightUpDto();
            string sign = "";
            string store = "";
            foreach (var routeway in routeways)
            {
                var priceTagsList = Context.TPriceTags.Where(x => x.CellCode == cellCode.FirstOrDefault()).ToList();
                if(priceTagsList.Count() <= 0)
                {
                    return roadwayLightUpDto;
                }
                sign = priceTagsList.FirstOrDefault().Sign;
                store = priceTagsList.FirstOrDefault().Store_code;
                var lightModel = Context.TRoadwayLightModel.Where(x => x.RoadwayCode == routeway.Code);
                if(lightModel == null)
                {
                    msg = "暂未维护巷道灯信息";
                    return null;
                }
                RoadwayLightUpOrderDetailDto roadwayLightUpOrderDetailDto = new RoadwayLightUpOrderDetailDto();
                roadwayLightUpOrderDetailDto.esl_code = lightModel.FirstOrDefault().LightCode;
                R r = new R();
                r.off = 100;
                r.on = 100;
                r.work = 10000;
                r.psm = 255;
                Tunnel_led tunnel_Led = new Tunnel_led();
                tunnel_Led.r = r;
                roadwayLightUpOrderDetailDto.tunnel_led.Add(tunnel_Led);
                roadwayLightUpDto.f1.Add(roadwayLightUpOrderDetailDto);
                

            }
            roadwayLightUpDto.store_code = store;
            roadwayLightUpDto.sign = sign;
            return roadwayLightUpDto;

        }


        /// <summary>
        /// 查询熄灭巷道灯接口
        /// </summary>
        /// <param name="routeways"></param>
        /// <returns></returns>
        public RoadwayLightUpDto GetLightByRoadwayDown(out string msg, List<string> cellCode, List<TRouteway> routeways)
        {
            msg = "";
            RoadwayLightUpDto roadwayLightUpDto = new RoadwayLightUpDto();
            string sign = "";
            string store = "";
            foreach (var item in routeways)
            {
                var priceTagsList = Context.TPriceTags.Where(x => x.CellCode == cellCode.FirstOrDefault()).ToList();
                if (priceTagsList.Count() <= 0)
                {
                    return roadwayLightUpDto;
                }
                sign = priceTagsList.FirstOrDefault().Sign;
                store = priceTagsList.FirstOrDefault().Store_code;
                var lightModel = Context.TRoadwayLightModel.Where(x => x.RoadwayCode == item.Code);
                if (lightModel == null)
                {
                    msg = "暂未维护巷道灯信息";
                    return null;
                }
                RoadwayLightUpOrderDetailDto roadwayLightUpOrderDetailDto = new RoadwayLightUpOrderDetailDto();
                roadwayLightUpOrderDetailDto.esl_code = lightModel.FirstOrDefault().LightCode;
                R r = new R();
                r.off = 0;
                r.on = 0;
                r.work = 0;
                r.psm = 255;
                Tunnel_led tunnel_Led = new Tunnel_led();
                tunnel_Led.r = r;
                roadwayLightUpOrderDetailDto.tunnel_led.Add(tunnel_Led);
                roadwayLightUpDto.f1.Add(roadwayLightUpOrderDetailDto);
            }

            roadwayLightUpDto.store_code = store;
            roadwayLightUpDto.sign = sign;
            return roadwayLightUpDto;

        }

        /// <summary>
        /// 巷道灯点亮接口
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public RFIDMsgDto RoadwayLightUp(string path, object data)
        {
            RFIDMsgDto rfidMsgDto = new RFIDMsgDto();

            try
            {
                //string wcsUrl = "http://172.16.99.12:28086/";
                string rfidUrl = "http://192.168.1.100/";
                string url = rfidUrl + path;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                string jsonData = JsonConvert.SerializeObject(data);

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonData);
                }



                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // 检查响应状态码
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string jsonResponse = reader.ReadToEnd(); // 读取服务器响应的内容
                            rfidMsgDto = JsonConvert.DeserializeObject<RFIDMsgDto>(jsonResponse);
                            if (rfidMsgDto.error_code != 1)
                            {
                                return rfidMsgDto;
                            }
                        }
                        rfidMsgDto.error_code = 0;
                        rfidMsgDto.error_msg = "成功";
                        return rfidMsgDto;
                    }
                    else
                    {
                        rfidMsgDto.error_code = 1;
                        rfidMsgDto.error_msg = "HTTP请求失败，状态码：" + response.StatusCode;
                        return rfidMsgDto;
                    }
                }
            }
            catch (Exception)
            {
                // 处理异常情况
                rfidMsgDto.error_code = 1;
                rfidMsgDto.error_msg = "HTTP请求失败，状态码：500";
                return rfidMsgDto;
            }
        }


        /// <summary>
        /// 巷道灯熄灭接口
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public RFIDMsgDto RoadwayLightExtinguish(string path, object data)
        {
            RFIDMsgDto rfidMsgDto = new RFIDMsgDto();

            try
            {
                //string wcsUrl = "http://172.16.99.12:28086/";
                string rfidUrl = "http://192.168.1.100/";
                string url = rfidUrl + path;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                string jsonData = JsonConvert.SerializeObject(data);

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonData);
                }



                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // 检查响应状态码
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string jsonResponse = reader.ReadToEnd(); // 读取服务器响应的内容
                            rfidMsgDto = JsonConvert.DeserializeObject<RFIDMsgDto>(jsonResponse);
                            if (rfidMsgDto.error_code != 1)
                            {
                                return rfidMsgDto;
                            }
                        }
                        rfidMsgDto.error_code = 0;
                        rfidMsgDto.error_msg = "成功";
                        return rfidMsgDto;
                    }
                    else
                    {
                        rfidMsgDto.error_code = 1;
                        rfidMsgDto.error_msg = "HTTP请求失败，状态码：" + response.StatusCode;
                        return rfidMsgDto;
                    }
                }
            }
            catch (Exception)
            {
                // 处理异常情况
                rfidMsgDto.error_code = 1;
                rfidMsgDto.error_msg = "HTTP请求失败，状态码：500";
                return rfidMsgDto;
            }
        }




        /// <summary>
        /// 根据托盘查询相关信息
        /// </summary>
        /// <param name="cellCodeList"></param>
        /// <returns></returns>
        public PriceTagIlluminatedDto GetMsgByCellCode(List<string> cellCodeList)
        {
            PriceTagIlluminatedDto priceTags = new PriceTagIlluminatedDto();
            List<string> f1s = new List<string>();
            foreach (string cellCode in cellCodeList)
            {
                string f1 = "";
                var priceTagsModel = Context.TPriceTags.Where(x => x.CellCode == cellCode).ToList();
                if (priceTagsModel.Count <= 0)
                {
                    continue;
                }
                f1 = priceTagsModel.FirstOrDefault().PriceTagsUrl;
                f1s.Add(f1);
            }
            priceTags.f1 = f1s;
            var rfidMsg = Context.TPriceTags.First();
            priceTags.store_code = rfidMsg.Store_code;
            priceTags.sign = rfidMsg.Sign;
            return priceTags;

        }

        /// <summary>
        /// 根据仓位查询相关信息
        /// </summary>
        /// <param name="cellCodeList"></param>
        /// <returns></returns>
        public RFIDLampDirectDto GetRFIDMsgByCellCode(List<string> cellCodeList)
        {
            RFIDLampDirectDto priceTags = new RFIDLampDirectDto();
            foreach (string cellCode in cellCodeList)
            {
                var priceTagsModel = Context.TPriceTags.Where(x => x.CellCode == cellCode).ToList();
                if (priceTagsModel.Count <= 0)
                {
                    continue;
                }
                Led led = new Led();
                led.r = 255;
                led.g = 0;
                led.b = 0;
                led.time_on = 1000;
                led.time = 10000;

                F1 f1 = new F1();
                f1.esl_code = priceTagsModel.FirstOrDefault().PriceTagsUrl;
                f1.template_id = 1;
                f1.product = null;
                f1.led.Add(led);
                priceTags.f1.Add(f1);

            }

            var rfidMsg = Context.TPriceTags.First();
            priceTags.store_code = rfidMsg.Store_code;
            priceTags.sign = rfidMsg.Sign;
            priceTags.is_base64 = "0";
            

            return priceTags;

        }


        /// <summary>
        /// 根据仓位查询相关信息（熄灭）
        /// </summary>
        /// <param name="cellCodeList"></param>
        /// <returns></returns>
        public RFIDLampDirectDto GetRFIDMsgByCellCodeExtinguish(List<string> cellCodeList)
        {
            RFIDLampDirectDto priceTags = new RFIDLampDirectDto();
            foreach (string cellCode in cellCodeList)
            {
                var priceTagsModel = Context.TPriceTags.Where(x => x.CellCode == cellCode).ToList();
                if (priceTagsModel.Count <= 0)
                {
                    continue;
                }
                Led led = new Led();
                led.r = 255;
                led.g = 0;
                led.b = 0;
                led.time_on = 0;
                led.time = 0;

                F1 f1 = new F1();
                f1.esl_code = priceTagsModel.FirstOrDefault().PriceTagsUrl;
                f1.template_id = 1;
                f1.product = null;
                f1.led.Add(led);
                priceTags.f1.Add(f1);

            }

            var rfidMsg = Context.TPriceTags.First();
            priceTags.store_code = rfidMsg.Store_code;
            priceTags.sign = rfidMsg.Sign;
            priceTags.is_base64 = "0";


            return priceTags;

        }


        /// <summary>
        /// 查询环境
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public RFIDMsgDto BindMaterialAddRFID(string path, object data)
        {
            RFIDMsgDto rfidMsgDto = new RFIDMsgDto();

            try
            {
                //string wcsUrl = "http://172.16.99.12:28086/";
                string wcsUrl = "http://localhost/";
                string url = wcsUrl + path;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                string jsonData = JsonConvert.SerializeObject(data);

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonData);
                }



                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // 检查响应状态码
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string jsonResponse = reader.ReadToEnd(); // 读取服务器响应的内容
                            rfidMsgDto = JsonConvert.DeserializeObject<RFIDMsgDto>(jsonResponse);
                            if (rfidMsgDto.error_code != 1)
                            {
                                return rfidMsgDto;
                            }
                        }
                        rfidMsgDto.error_code = 0;
                        rfidMsgDto.error_msg = "成功";
                        return rfidMsgDto;
                    }
                    else
                    {
                        rfidMsgDto.error_code = 1;
                        rfidMsgDto.error_msg = "HTTP请求失败，状态码：" + response.StatusCode;
                        return rfidMsgDto;
                    }
                }
            }
            catch (Exception)
            {
                // 处理异常情况
                rfidMsgDto.error_code = 1;
                rfidMsgDto.error_msg = "HTTP请求失败，状态码：500";
                return rfidMsgDto;
            }
        }


        /// <summary>
        /// 标签点亮
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public RFIDMsgDto RFIDLightUp(string path, object data)
        {
            RFIDMsgDto rfidMsgDto = new RFIDMsgDto();

            try
            {
                //string wcsUrl = "http://172.16.99.12:28086/";
                string rfidUrl = "http://192.168.1.100/";
                string url = rfidUrl + path;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                string jsonData = JsonConvert.SerializeObject(data);

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonData);
                }



                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // 检查响应状态码
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string jsonResponse = reader.ReadToEnd(); // 读取服务器响应的内容
                            rfidMsgDto = JsonConvert.DeserializeObject<RFIDMsgDto>(jsonResponse);
                            if (rfidMsgDto.error_code != 0)
                            {
                                return rfidMsgDto;
                            }
                        }
                        rfidMsgDto.error_code = 0;
                        rfidMsgDto.error_msg = "成功";
                        return rfidMsgDto;
                    }
                    else
                    {
                        rfidMsgDto.error_code = 1;
                        rfidMsgDto.error_msg = "HTTP请求失败，状态码：" + response.StatusCode;
                        return rfidMsgDto;
                    }
                }
            }
            catch (Exception)
            {
                // 处理异常情况
                rfidMsgDto.error_code = 1;
                rfidMsgDto.error_msg = "HTTP请求失败，状态码：500";
                return rfidMsgDto;
            }
        }



        /// <summary>
        /// 标签熄灭
        /// </summary>
        /// <param name="path"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public RFIDMsgDto RFIDLightDown(string path, object data)
        {
            RFIDMsgDto rfidMsgDto = new RFIDMsgDto();

            try
            {
                //string wcsUrl = "http://172.16.99.12:28086/";
                string rfidUrl = "http://192.168.1.100/";
                string url = rfidUrl + path;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "application/json";

                string jsonData = JsonConvert.SerializeObject(data);

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(jsonData);
                }



                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    // 检查响应状态码
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string jsonResponse = reader.ReadToEnd(); // 读取服务器响应的内容
                            rfidMsgDto = JsonConvert.DeserializeObject<RFIDMsgDto>(jsonResponse);
                            if (rfidMsgDto.error_code != 0)
                            {
                                return rfidMsgDto;
                            }
                        }
                        rfidMsgDto.error_code = 0;
                        rfidMsgDto.error_msg = "成功";
                        return rfidMsgDto;
                    }
                    else
                    {
                        rfidMsgDto.error_code = 1;
                        rfidMsgDto.error_msg = "HTTP请求失败，状态码：" + response.StatusCode;
                        return rfidMsgDto;
                    }
                }
            }
            catch (Exception)
            {
                // 处理异常情况
                rfidMsgDto.error_code = 1;
                rfidMsgDto.error_msg = "HTTP请求失败，状态码：500";
                return rfidMsgDto;
            }
        }

        /// <summary>
        /// 点亮标签 单个仓位查询
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="cellCode"></param>
        /// <returns></returns>
        public RFIDLampDirectDto GetRFIDMsgByCellCode(out string msg,string cellCode)
        {
            msg = "";
            try
            {
                RFIDLampDirectDto lampDirectDto = new RFIDLampDirectDto();
                var priceTagsList = Context.TPriceTags.Where(x => x.CellCode == cellCode);
                if (priceTagsList.Count() <= 0)
                {

                    return null;
                }
                lampDirectDto.store_code = priceTagsList.FirstOrDefault().Store_code;
                lampDirectDto.is_base64 = "0";
                lampDirectDto.sign = priceTagsList.FirstOrDefault().Sign;
                F1 f1 = new F1();
                f1.esl_code = priceTagsList.FirstOrDefault().PriceTagsUrl;
                f1.template_id = 1;
                Product product = new Product();
                f1.product = product;
                Led led = new Led();
                led.r = 255;
                led.g = 0;
                led.b = 0;
                led.time_on = 100;
                led.time = 10000;
                f1.led.Add(led);
                lampDirectDto.f1.Add(f1);

                return lampDirectDto;
            }
            catch
            {
                msg = "请求失败，状态码为500";
                return null;
            }
          
        }
    }
}
